package cz.matasek.dbLogger.gui;

import java.util.Comparator;

/**
 * Implementation of default ordering function.
 * Inspired by 
 * <a href="http://www.java-forums.org/advanced-java/1794-sorting-jtable.html">
 * http://www.java-forums.org/advanced-java/1794-sorting-jtable.html</a>.
 *
 * @author Luboš Matásek
 */
public class UniversalComparator implements Comparator {

    /**
     * Compares its two arguments for order. Returns a negative integer,
     * zero, or a positive integer as the first argument is less than, equal
     * to, or greater than the second.
     *
     * @param o1 the first object to be compared
     * @param o2 the second object to be compared
     * @return a negative integer, zero, or a positive integer as the first
     * argument is less than, equal to, or greater than the second
     */
    @Override
    @SuppressWarnings("unchecked")
    public int compare(Object o1, Object o2) {
        // Treat empty strains like nulls
        if (o1 instanceof String && ((String) o1).length() == 0) {
            o1 = null;
        }
        if (o2 instanceof String && ((String) o2).length() == 0) {
            o2 = null;
        }

        // Sort nulls so they appear last, regardless
        // of sort order
        if (o1 == null && o2 == null) {
            return 0;
        } else if (o1 == null) {
            return 1;
        } else if (o2 == null) {
            return -1;
        } else if (o1 instanceof Comparable) {
            return ((Comparable) o1).compareTo(o2);
        } else {
            return o1.toString().compareTo(o2.toString());
        }
    }
}